package me.android.library.utils.android;

import android.content.Context;
import android.provider.Settings;

import com.google.common.base.Strings;

import java.io.InputStreamReader;
import java.io.LineNumberReader;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class ClientUtil {

    /**
     * 获取设备唯一标识符
     */
    public String getClientId() {
        Context cx = ContextUtil.getAppContext();

        String token = getMacByShellCmd();

        if (Strings.isNullOrEmpty(token)) {
            token = NetworkUtil.getLocalMac();
        }

        if (Strings.isNullOrEmpty(token)) {
            token = LinuxUtil.getMacAddress();
        }

        if (Strings.isNullOrEmpty(token)) {
            token = Settings.System.getString(cx.getContentResolver(), Settings.Secure.ANDROID_ID);
        }

        return token;
    }

    String getMacByShellCmd() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            while (null != str) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception e) {
            log.warn("getMacByShellCmd error", e);
        }
        return macSerial;
    }

}
